package com.zfei.gfb.controller;

import cn.hutool.core.date.DateUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.JsonObject;
import com.zfei.gfb.api.StatsService;
import com.zfei.gfb.api.domain.StatsTag;
import com.zfei.gfb.api.domain.StatsValue;
import com.zfei.gfb.api.domain.TalkEvent;
import com.zfei.gfb.bean.Const;
import com.zfei.gfb.bean.Status;
import com.zfei.gfb.bean.StatusException;
import com.zfei.gfb.core.Auth;
import com.zfei.gfb.core.HttpJson;
import com.zfei.gfb.core.LogResult;
import com.zfei.gfb.dao.GfbHouseMapper;
import com.zfei.gfb.dao.GfbVillagerMapper;
import com.zfei.gfb.device.AppContext;
import com.zfei.gfb.model.GfbHouse;
import com.zfei.gfb.model.GfbVillager;
import com.zfei.gfb.query.GfbHouseQuery;
import com.zfei.gfb.request.GfbGetRequest;
import com.zfei.gfb.request.GfbHouseAddRequest;
import com.zfei.gfb.request.GfbHouseAuditRequest;
import com.zfei.gfb.request.GfbDelRequest;
import com.zfei.gfb.util.Beans;
import com.zfei.gfb.util.Gsons;
import com.zfei.gfb.util.Now;
import com.zfei.gfb.util.gson.Types;
import com.zfei.gfb.vo.GfbBannerListVo;
import com.zfei.gfb.vo.GfbHouseListVo;
import com.zfei.gfb.vo.GfbHouseVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author
 * @version 1.0
 */
@Auth(type = {Const.VILLAGE_MANAGER, Const.TOWN_MANAGER})
@Api(tags = "房屋租赁管理接口")
@RestController
@RequestMapping("/web/house")
public class GfbHouseController {

    @Resource
    private GfbHouseMapper gfbHouseMapper;

    @Resource
    private StatsService statsService;

    @Resource
    private GfbVillagerMapper gfbVillagerMapper;

    @ApiOperation(value = "后台房源发布")
    @ApiResponses({
            @ApiResponse(code = 200, message = "房源发布", response = GfbHouseVo.class),
    })
    @LogResult
    @HttpJson("/add")
    public Object add(@RequestBody GfbHouseAddRequest request) {

        request.checkInsertNull();
        GfbHouse record = Beans.copy(request, GfbHouse.class);
        record.setImages(Gsons.toJson(request.getImages()));

        GfbVillager villager = gfbVillagerMapper.selectByPrimaryKey(request.getUserId());
        if (villager == null) {
            throw new StatusException(Status.NOT_EXIST);
        }

        record.setPutonStatus(Const.STATUS_ON);
        record.setUserId(villager.getId());
        record.setPubTime(Now.millis());
        record.setStatus(Const.HOUSE_STATUS_ING);
        record.setCreateTime(Now.millis());
        record.setUpdateTime(Now.millis());
        record.setCntime(DateUtil.now());
        Map<String, String> ext = Maps.newHashMap();
        ext.put("from", "admin");
        record.setExt(Gsons.toJson(ext));

        gfbHouseMapper.insertSelective(record);

        GfbHouseVo vo = Beans.copy(record, GfbHouseVo.class);
        return vo;
    }

    @ApiOperation(value = "列表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = GfbHouseListVo.class),
    })
    @LogResult
    @HttpJson("/list")
    public Object list(@RequestBody GfbHouseQuery query) {
        query.check().build(Now::millis);

        GfbHouseListVo result = new GfbHouseListVo();

        int total = gfbHouseMapper.total(query);
        result.setTotal(total);
        if (total == 0) {
            result.setData(Lists.newArrayList());
            return result;
        }

        List<GfbHouse> records = gfbHouseMapper.list(query);
        List<GfbHouseVo> vos = new ArrayList<>();

        for (GfbHouse record : records) {
            GfbHouseVo vo = Beans.copy(record, GfbHouseVo.class);
            //房屋图片
            List<String> images = Gsons.fromJson(record.getImages(), Types.StringListType);
            vo.setImages(images);
            //消防图片
            List<String> checkImages = Gsons.fromJson(record.getCheckImages(), Types.StringListType);
            vo.setCheckImages(checkImages);

            vo.setBrowseNum(statsService.get(vo.getId().toString(), StatsTag.HOUSE_BROWSE_COUNT).getNum());
            vos.add(vo);
        }

        result.setData(vos);
        return result;

    }

    @ApiOperation(value = "删除")
    @LogResult
    @HttpJson("/del")
    public Object del(@RequestBody GfbDelRequest request) {
        request.checkDelNull();
        Integer id = request.getId();

        GfbHouse record = gfbHouseMapper.selectByPrimaryKey(id);
        if (record == null) {
            throw new StatusException(Status.NOT_EXIST);
        }
        //删除预约列表记录 todo
//		gfbHouseApplyMapper.deleteByHourseId(id);

        gfbHouseMapper.deleteByPrimaryKey(id);
        return null;
    }

    @ApiOperation(value = "审核")
    @LogResult
    @HttpJson("/audit")
    public Object audit(@RequestBody GfbHouseAuditRequest request) {
        request.checkUpdateNull();

        Integer id = request.getId();
        Integer status = request.getStatus();
        String reason = request.getReason();
        List<String> checkImages = request.getCheckImages();


        GfbHouse record = gfbHouseMapper.selectByPrimaryKey(id);
        if (record == null) {
            throw new StatusException(Status.NOT_EXIST);
        }
        if (status == Const.HOUSE_STATUS_OFF) {
            record.setPutonStatus(Const.STATUS_OFF);
            record.setReason(reason);
        }

        record.setStatus(status);
        record.setCheckImages(Gsons.toJson(checkImages));
        record.setUpdateTime(Now.millis());
        gfbHouseMapper.updateByPrimaryKeySelective(record);

        return null;
    }

    @ApiOperation(value = "详情")
    @ApiResponses({
            @ApiResponse(code = 200, message = "房源详情", response = GfbHouseVo.class),
    })
    @LogResult
    @HttpJson("/get")
    public Object get(@RequestBody GfbGetRequest request) {
        request.checkGetNull();
        Integer id = request.getId();

        GfbHouse record = gfbHouseMapper.selectByPrimaryKey(id);
        GfbHouseVo vo = Beans.copy(record, GfbHouseVo.class);
        //房屋图片
        List<String> images = Gsons.fromJson(record.getImages(), Types.StringListType);
        vo.setImages(images);
        //消防图片
        List<String> checkImages = Gsons.fromJson(record.getCheckImages(), Types.StringListType);
        vo.setCheckImages(checkImages);

        String ext = record.getExt();

        String from;
        if (StringUtils.isBlank(ext)) {
            from = "client";
        } else {
            JsonObject jsonObject = Gsons.parseJsonObject(ext);
            if (jsonObject.has("from")) {
                from = jsonObject.get("from").getAsString();
            } else {
                from = "client";
            }
        }

        Integer userId = record.getUserId();
        GfbVillager villager = gfbVillagerMapper.selectByPrimaryKey(userId);
        if (villager != null) {
            vo.setUserName(villager.getName());
            vo.setVillagerName(villager.getVillagerName());
        }

        vo.setFrom(from);
        return vo;
    }
}
